/**
 * 客户档案管理模块 - Mock数据集合
 * @description 生成完整的客户模拟数据集
 * @author CRM开发团队
 * @version 1.0.0
 */

import Mock from 'mockjs'
import {
  CUSTOMER_STATUS,
  HEALTH_STATUS,
  generateChineseName,
  generateIdCard,
  generatePhoneNumber,
  generateCustomerTags,
  generateAddress,
  generateTravelPreferences,
  generateHealthInfo,
  generateFamilyInfo,
  OCCUPATIONS
} from './customer-data'
import type { 
  CustomerBasicInfo, 
  CustomerTag, 
  TravelPreferences, 
  HealthInfo, 
  FamilyInfo, 
  CustomerDetail 
} from '@/api/customer'

// ==========================================
// 类型定义
// ==========================================

// 使用API定义的接口，确保完全兼容
export interface MockCustomer extends Omit<CustomerBasicInfo, 'id' | 'customerCode' | 'age'> {
  id: number
  customerCode: string
  age: number
  address: string
  postalCode: string
  tags: CustomerTag[]  // 改为CustomerTag数组
  healthStatus: typeof HEALTH_STATUS[number]
  // 旅游偏好数据
  destinationPreference?: string[]
  budgetRange?: string
  monthlyContactCount?: number
  createdAt: string
  updatedAt: string
  lastContactTime: string
}

// ==========================================
// 数据生成器
// ==========================================

/**
 * 生成单个客户数据
 */
function generateSingleCustomer(id: number): MockCustomer {
  const gender = Mock.Random.pick(['男', '女'])
  const nameInfo = generateChineseName(gender)
  
  // 生成1950-1970年间的出生日期
  const birthYear = Mock.Random.integer(1950, 1970)
  const birthMonth = Mock.Random.integer(1, 12)
  const birthDay = Mock.Random.integer(1, 28)
  const birthDate = `${birthYear}-${birthMonth.toString().padStart(2, '0')}-${birthDay.toString().padStart(2, '0')}`
  const age = new Date().getFullYear() - birthYear

  const addressInfo = generateAddress()
  const emergencyContact = generateChineseName(gender === '男' ? '女' : '男')

  const createdDate = new Date(Date.now() - Mock.Random.integer(1, 90) * 24 * 60 * 60 * 1000)
  const updatedDate = new Date(createdDate.getTime() + Mock.Random.integer(0, 30) * 24 * 60 * 60 * 1000)
  const lastContactDate = new Date(updatedDate.getTime() + Mock.Random.integer(0, 7) * 24 * 60 * 60 * 1000)

  const hasReferrer = Mock.Random.boolean()
  
  // 生成旅游偏好数据
  const travelPrefs = generateTravelPreferences()
  
  // 生成目的地偏好数组
  const destinationPreferences = Mock.Random.pick([
    ['北京', '上海'],
    ['云南', '贵州', '四川'],
    ['桂林', '西安', '成都'],
    ['海南', '厦门'],
    ['江南', '华东', '华南'],
    ['东南亚', '日本'],
    ['欧洲', '澳洲'],
    ['国内精品线路'],
    ['温泉养生', '海滨度假'],
    ['历史古迹', '自然风光']
  ])
  
  return {
    id,
    customerCode: `CRM2024${id.toString().padStart(3, '0')}`,
    customerName: nameInfo.fullName,
    gender,
    birthDate,
    age,
    idCard: generateIdCard(birthYear),
    primaryPhone: generatePhoneNumber(),
    backupPhone: Mock.Random.boolean() ? generatePhoneNumber() : undefined,
    wechat: Mock.Random.boolean() ? nameInfo.fullName + birthYear : undefined,
    qq: Mock.Random.boolean() ? Mock.Random.string('number', 9) : undefined,
    email: Mock.Random.boolean() ? Mock.Random.email() : undefined,
    address: addressInfo.fullAddress,
    postalCode: Mock.Random.zip(),
    emergencyContactName: emergencyContact.fullName,
    emergencyContactRelation: Mock.Random.pick(['配偶', '子女', '亲属', '朋友']),
    emergencyContactPhone: generatePhoneNumber(),
    workStatus: Mock.Random.pick(['在职', '退休', '待业', '其他']),
    occupation: Mock.Random.pick(OCCUPATIONS),
    customerStatus: Mock.Random.pick(CUSTOMER_STATUS),
    referrerInfo: hasReferrer ? {
      referrerName: generateChineseName().fullName,
      referrerPhone: generatePhoneNumber(),
      referrerRelation: Mock.Random.pick(['朋友推荐', '老客户推荐', '网络推荐', '其他']),
      referrerTime: createdDate.toISOString()
    } : undefined,
    tags: generateCustomerTags(Mock.Random.integer(2, 5)),
    healthStatus: Mock.Random.pick(HEALTH_STATUS),
    // 添加旅游偏好数据
    destinationPreference: destinationPreferences,
    budgetRange: travelPrefs.budgetRange,
    monthlyContactCount: Mock.Random.integer(0, 15),
    createdAt: createdDate.toISOString(),
    updatedAt: updatedDate.toISOString(),
    lastContactTime: lastContactDate.toISOString()
  }
}

/**
 * 生成客户详细信息
 */
export function generateCustomerDetail(customer: MockCustomer) {
  return {
    basicInfo: customer,
    tags: customer.tags,
    travelPreferences: generateTravelPreferences(),
    healthInfo: generateHealthInfo(),
    familyInfo: generateFamilyInfo(),
    metadata: {
      createdAt: customer.createdAt,
      updatedAt: customer.updatedAt,
      createdBy: 1,
      updatedBy: 1
    }
  }
}


// ==========================================
// 预定义客户数据集
// ==========================================

/**
 * 精心设计的客户数据集合
 * 包含各种典型的客户类型和场景
 */
// 生成预定义标签的辅助函数
function createPredefinedTags(tagNames: string[]) {
  return tagNames.map((tagName, index) => {
    // 根据标签名称确定分类
    let category = '价值分类'
    if (['易沟通', '需要关怀', '决策慢', '冲动消费'].includes(tagName)) {
      category = '服务特点'
    } else if (['喜欢跟团', '偏爱自由行', '只走精品线', '价格敏感'].includes(tagName)) {
      category = '出行特点'
    } else if (['身体健康', '需要照顾', '行动不便'].includes(tagName)) {
      category = '健康状态'
    } else if (['多次消费', '首次消费', '犹豫不决', '果断下单'].includes(tagName)) {
      category = '消费习惯'
    }

    return {
      id: index + 1000, // 使用固定ID避免重复
      category,
      name: tagName,
      isSystem: true,
      createdAt: new Date().toISOString()
    }
  })
}

const PREDEFINED_CUSTOMERS: Partial<MockCustomer>[] = [
  // VIP客户
  {
    customerName: '张建国',
    gender: '男',
    birthDate: '1955-03-15',
    customerStatus: '已成交客户',
    tags: createPredefinedTags(['VIP客户', '易沟通', '喜欢跟团', '身体健康', '多次消费']),
    healthStatus: '健康良好',
    occupation: '工程师',
    workStatus: '退休',
    destinationPreference: ['北京', '上海', '江南'],
    budgetRange: '豪华型'
  },
  {
    customerName: '刘淑芬',
    gender: '女',
    birthDate: '1958-07-22',
    customerStatus: '已成交客户',
    tags: createPredefinedTags(['优质客户', '需要关怀', '只走精品线', '身体健康', '果断下单']),
    healthStatus: '健康一般',
    occupation: '教师',
    workStatus: '退休',
    destinationPreference: ['云南', '贵州', '四川'],
    budgetRange: '品质型'
  },
  
  // 有效客户
  {
    customerName: '王德华',
    gender: '男',
    birthDate: '1952-11-08',
    customerStatus: '有效客户',
    tags: createPredefinedTags(['VIP客户', '易沟通', '偏爱自由行', '需要照顾', '多次消费']),
    healthStatus: '健康较差',
    occupation: '医生',
    workStatus: '退休',
    destinationPreference: ['温泉养生', '海滨度假'],
    budgetRange: '舒适型'
  },
  {
    customerName: '陈桂花',
    gender: '女',
    birthDate: '1960-04-12',
    customerStatus: '有效客户',
    tags: createPredefinedTags(['普通客户', '决策慢', '喜欢跟团', '身体健康', '犹豫不决']),
    healthStatus: '健康良好',
    occupation: '护士',
    workStatus: '退休',
    destinationPreference: ['桂林', '西安', '成都'],
    budgetRange: '舒适型'
  },
  
  // 潜在客户
  {
    customerName: '李国强',
    gender: '男',
    birthDate: '1956-09-25',
    customerStatus: '潜在客户',
    tags: createPredefinedTags(['价格敏感客户', '易沟通', '价格敏感', '身体健康', '首次消费']),
    healthStatus: '健康良好',
    occupation: '公务员',
    workStatus: '退休',
    destinationPreference: ['国内精品线路'],
    budgetRange: '经济型'
  },
  {
    customerName: '赵美玲',
    gender: '女',
    birthDate: '1959-12-03',
    customerStatus: '潜在客户',
    tags: createPredefinedTags(['普通客户', '需要关怀', '喜欢跟团', '需要照顾', '首次消费']),
    healthStatus: '健康一般',
    occupation: '会计',
    workStatus: '退休',
    destinationPreference: ['海南', '厦门'],
    budgetRange: '舒适型'
  },
  
  // 无效客户
  {
    customerName: '孙建明',
    gender: '男',
    birthDate: '1954-06-18',
    customerStatus: '无效客户',
    tags: createPredefinedTags(['价格敏感客户', '决策慢', '价格敏感']),
    healthStatus: '健康很差',
    occupation: '工人',
    workStatus: '退休',
    destinationPreference: ['周边短途'],
    budgetRange: '经济型'
  },
  {
    customerName: '周秀英',
    gender: '女',
    birthDate: '1957-01-30',
    customerStatus: '无效客户',
    tags: createPredefinedTags(['普通客户', '犹豫不决']),
    healthStatus: '健康较差',
    occupation: '服务员',
    workStatus: '退休',
    destinationPreference: ['本地景点'],
    budgetRange: '经济型'
  }
]

// ==========================================
// 导出数据集合
// ==========================================

/**
 * 生成完整的客户数据集合
 */
function generateCustomerDataset(): MockCustomer[] {
  const customers: MockCustomer[] = []
  
  // 先生成预定义的客户数据
  PREDEFINED_CUSTOMERS.forEach((preset, index) => {
    const customer = generateSingleCustomer(index + 1)
    // 覆盖预设字段
    Object.assign(customer, preset)
    
    // 重新计算年龄
    if (preset.birthDate) {
      const birthYear = parseInt(preset.birthDate.split('-')[0])
      customer.age = new Date().getFullYear() - birthYear
      customer.idCard = generateIdCard(birthYear)
    }
    
    customers.push(customer)
  })
  
  // 生成剩余的随机客户数据
  const totalCount = 50 // 总共生成50个客户
  for (let i = PREDEFINED_CUSTOMERS.length; i < totalCount; i++) {
    customers.push(generateSingleCustomer(i + 1))
  }
  
  return customers
}

// 生成并导出客户数据集
export const MOCK_CUSTOMERS = generateCustomerDataset()

// 导出统计数据
export const CUSTOMER_STATISTICS = {
  total: MOCK_CUSTOMERS.length,
  byStatus: CUSTOMER_STATUS.reduce((acc, status) => {
    acc[status] = MOCK_CUSTOMERS.filter(c => c.customerStatus === status).length
    return acc
  }, {} as Record<string, number>),
  byGender: {
    '男': MOCK_CUSTOMERS.filter(c => c.gender === '男').length,
    '女': MOCK_CUSTOMERS.filter(c => c.gender === '女').length
  },
  byAge: {
    '50-59岁': MOCK_CUSTOMERS.filter(c => c.age >= 50 && c.age < 60).length,
    '60-64岁': MOCK_CUSTOMERS.filter(c => c.age >= 60 && c.age < 65).length,
    '65-69岁': MOCK_CUSTOMERS.filter(c => c.age >= 65 && c.age < 70).length,
    '70-74岁': MOCK_CUSTOMERS.filter(c => c.age >= 70 && c.age < 75).length,
    '75岁以上': MOCK_CUSTOMERS.filter(c => c.age >= 75).length
  },
  byHealth: HEALTH_STATUS.reduce((acc, status) => {
    acc[status] = MOCK_CUSTOMERS.filter(c => c.healthStatus === status).length
    return acc
  }, {} as Record<string, number>)
}

// 导出工具函数
export {
  generateSingleCustomer
}